package com.ums.upos.service;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.ums.upos.uapi.network.NetWorkParams;
import com.ums.upos.uapi.network.WifiParam;
import com.ums.upos.util.SharedPreferencesUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by liyang on 15-6-4.
 */
public class WifiAdmin {
    private static final String TAG = "WifiAdmin";
    private static WifiAdmin singleton = new WifiAdmin();
    // 定义一个WifiLock
    WifiManager.WifiLock mWifiLock;
    StringBuilder sb;
    String SSID;
    String Password;
    int Type;
    Context context;
    private String mac;
    private Logger log = LoggerFactory.getLogger(TAG);
    private String ipAddress, getWay, dns1, dns2;
    private boolean isDhcp = true;

    public void setStaticIp(String ipAddress, String getWay, String dns1, String dns2) {
        isDhcp = false;
        this.ipAddress = ipAddress;
        this.getWay = getWay;
        this.dns1 = dns1;
        this.dns2 = dns2;
    }

    public String getMac() {
        return mac;
    }

    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表
    private List<ScanResult> mWifiList;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfiguration;

    public static WifiAdmin getInstance() {
        return singleton;
    }

    // 构造器
    public void init(Context context,
                     String SSID, String Password, int Type) {

        this.context = context;
        this.SSID = SSID;
        this.Password = Password;
        this.Type = Type;
        // 取得WifiManager对象
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 构造器
    public void init(Context context) {
        this.context = context;
        // 取得WifiManager对象
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
        mac = mWifiInfo.getMacAddress();// 获得本机的MAC地址
    }

    //打开wifi
    public boolean enableWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
        // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右)，所以要等到wifi
        // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
        log.debug("first getWifiState {}", mWifiManager.getWifiState());
        long beginTime = System.currentTimeMillis();
        while (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
            log.debug("getWifiState:" + mWifiManager.getWifiState());
            if (System.currentTimeMillis() - beginTime > 10 * 1000) {
                return false;
            }
            try {
                // 为了避免程序一直while循环，让它睡个100毫秒检测……
                Thread.sleep(100);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
        return true;
    }

    // 连接wifi
    public boolean openWifi(int wcgID) {
        if (enableWifi()) {
            return enableNetwork(wcgID);
        }
        return false;
    }

    // 关闭WIFI
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
        log.debug("first getWifiState {}", mWifiManager.getWifiState());
        long beginTime = System.currentTimeMillis();
        while (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
            log.debug("getWifiState:" + mWifiManager.getWifiState());
            if (System.currentTimeMillis() - beginTime > 10 * 1000) {
                return;
            }
            try {
                // 为了避免程序一直while循环，让它睡个100毫秒检测……
                Thread.sleep(100);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }

    // 检查当前WIFI状态
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock
    public void releaseWifiLock() {
        // 判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;
    }

    // 指定配置好的网络进行连接
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回
        if (index > mWifiConfiguration.size()) {
            return;
        }
        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
    }

    // 指定配置好的网络进行连接
    public void connectConfigurationByNetworkID(int networkId) {

        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(networkId, true);
    }

    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的网络连接
//        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到网络列表
    public List<ScanResult> getWifiList() {
        return mWifiList;
    }

    // 查看扫描结果
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++) {
            stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括：BSSID、SSID、capabilities、frequency、level
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 得到连接的ID
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 添加一个网络并连接
    public int addNetwork() {
        enableWifi();
        WifiConfiguration wcg = CreateWifiInfo(SSID, Password, Type);
        return mWifiManager.addNetwork(wcg);
    }

    // 连接
    public boolean enableNetwork(int wcgID) {
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        log.debug("enableNetwork " + b);
        if (!b) {
            return false;
        }
        long beginTime = System.currentTimeMillis();
        while (true) {
            if (System.currentTimeMillis() - beginTime > 20 * 1000) {
                return false;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null) {
                    for (NetworkInfo anInfo : info) {
                        if (anInfo.getTypeName().equals("WIFI") && anInfo.isConnected()) {
                            return true;
                        }
                    }
                }
//                NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
//                if (networkInfo != null) {
//                    if (networkInfo.isAvailable() && networkInfo.isConnected()) {
//                        if (NetworkInfo.State.CONNECTED == connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()) {
//                            return true;
//                        }
//                    }
//                }
            }
        }

//        int i=0;
//        for(WifiConfiguration item:mWifiManager.getConfiguredNetworks()){
//            AppLogger.d(TAG,"index:"+(i++)+" networkId:"+item.networkId+" ssid:"+item.SSID);
//        }
    }

    public StringBuilder getSb() {
        return sb;
    }

    // 断开指定ID的网络
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

//然后是一个实际应用方法，只验证过没有密码的情况：

    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        log.debug("ssid:" + SSID + " pwd:" + Password + " type:" + Type);

        int networkId = mWifiManager.getConnectionInfo().getNetworkId();
        mWifiManager.removeNetwork(networkId);

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = quote(SSID);

        if (Type == WifiParam.CIPHERTYPE_NOPASSWORD) //WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = quote(Password);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiParam.CIPHERTYPE_WEP) //WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = quote(Password);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiParam.CIPHERTYPE_WPA2_PSK) //WIFICIPHER_WPA
        {
            config.preSharedKey = quote(Password);
            config.hiddenSSID = true;
            config.priority = 40;
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        if (!(SharedPreferencesUtil.getInstance(context).getBoolean(NetWorkParams.WIFI_ISDHCP))) {
            new StaticIpSet(context, ipAddress, getWay, dns1, dns2).confingStaticIp(config);
        }
        log.debug("config:" + config);
        return config;
    }

    //    private WifiConfiguration IsExsits(String SSID) {
//        log.debug("wifistate:" + mWifiManager.getWifiState());
//        log.debug("enabled:" + mWifiManager.isWifiEnabled());
//        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
//        if(existingConfigs == null){
//            log.debug("getConfiguredNetworks = null");
//            return null;
//        }
//        for (WifiConfiguration existingConfig : existingConfigs) {
//            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
//                log.debug("configuration exist");
//                return existingConfig;
//            }
//        }
//        return null;
//    }
    private static String quote(String str) {
        return String.format("\"%s\"", str);
    }
}
